package com.zmx.core.client.log;

import com.zmx.core.dto.RequestLogInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 客户端日志服务类
 * @ClassName: LogInfoService
 * @Author zhaomxr
 * @Date 2021-12-24 09:39
 */
@Slf4j
@Component
public class LogInfoHandler {

    @Value("${job.logging.path}")
    private static String loggingPath;

    public RequestLogInfo getLog(RequestLogInfo requestLogInfo) {
        RequestLogInfo result = randomRed(requestLogInfo);
        return result;
    }

    /**
     * 读取文件
     **/
    public static RequestLogInfo randomRed(RequestLogInfo requestLogInfo) {
        List<String> logInfo = new ArrayList<String>(16);
        try {
            String path = StringUtils.isEmpty(loggingPath) ? "/logs/execute/mall-job-execute.log" : loggingPath;

            long pointer = requestLogInfo.getPointer();
            long rows = requestLogInfo.getRows() < 0 ? 10 : requestLogInfo.getRows();

            File file = new File(path);
            if (file == null) {
                System.out.println("文件不存在");
                return requestLogInfo;
            }

            RandomAccessFile raf = new RandomAccessFile(file, "r");
            if (pointer <= -1) {
                pointer = raf.length() - 1;
                rows = 100;
            }

            while (rows > 0) {
                //移动文件指针位置
                raf.seek(pointer);
                String line = null;
                //循环读取
                while ((line = raf.readLine()) != null) {
                    if (line.equals("")) {
                        continue;
                    }
                    //打印读取的内容,并将字节转为字符串输入，做转码处理，要不然中文会乱码
                    line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
                    logInfo.add(line);
                }

                rows--;
                //文件读取完毕后，将文件指针游标设置为当前指针位置
                pointer = raf.getFilePointer();
            }

            requestLogInfo.setContent(logInfo);
            requestLogInfo.setPointer(pointer);
        } catch (Exception e) {
            log.error("读取日志异常：" + e.getMessage(), e);
        }

        return requestLogInfo;
    }
}
